﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WorlducClient
{
    public partial class FrmExcelCompare : Form
    {
        public FrmExcelCompare()
        {
            InitializeComponent();
        }

        private void btnOpen1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                txtFile1.Text = dlg.FileName;
            }
        }

        private void btnOpen2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFile2.Text = dlg.FileName;
            }
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(new ThreadStart(comparefile));
            th.Start();            
        }

        private delegate void disp(string msg);
        private void dispmsg(string msg)
        {
            lblMsg.Text = msg;
        }
        private void txtAppend(string msg)
        {
            tbRes.AppendText(msg + "  ");
        }
        private void comparefile() {
            DataTable dt1 = ExcelUtil.ImportExceltoDt(txtFile1.Text,0,1);
            DataTable dt2 = ExcelUtil.ImportExceltoDt(txtFile2.Text,0,1);
            disp dmsg = new disp(dispmsg);
            disp tappend = new disp(txtAppend);
            for (int i = dt1.Rows.Count - 1; i >= 0; i--)
            {
                string where = string.Format("原位置='{0}' and 登记日期='{1}' and 亡故者姓名='{2}'",
                    dt1.Rows[i]["原位置"], dt1.Rows[i]["登记日期"], dt1.Rows[i]["亡故者姓名"]);
                DataRow[] drs = dt2.Select(where);
                if (drs != null && drs.Length > 0)
                {
                    dt1.Rows.RemoveAt(i);
                }
                else
                {
                    Invoke(tappend, i + "");
                }
                Invoke(dmsg, i + "");
            }
            ExcelUtil.ExportDTtoExcel(dt1, "比较结果", "d:\\a.xls");
            Invoke(tappend, "比较完成！");
        }
    }
}
